<?php

namespace App\Console\Commands\ES;

use App\Console\Commands\Common\CommonCommand;
use GuzzleHttp\Client;

class ESInit extends CommonCommand {

    protected $signature = 'es:init {index}' ;

    public function handle() {

        $index = $this->argument('index');
        $client = new Client();
        $url = config('scout.elasticsearch.hosts')[0].'/_template/tmp';
        /*
     * 这个模板作用于我要做用的索引
     * */
        $param = [
            'json'=>[
                /*
                 * 这句是取在scout.php（scout是驱动）里我们配置好elasticsearch引擎的
                 * index项。
                 * PS：其实都是取数组项，scout本身就是return一个数组，
                 * scout.elasticsearch.index就是取
                 * scout[elasticsearch][index]
                 * */
                'template'=>$index,
                'mappings'=>[
                    '_default_'=>[
                        'dynamic_templates'=>[
                            [
                                'string'=>[
                                    'match_mapping_type'=>'string',//传进来的是string
                                    'mapping'=>[
                                        'type'=>'text',//把传进来的string按text（文本）处理
                                        'analyzer'=>'ik_smart',//用ik_smart进行解析（ik是专门解析中的插件）
                                        'fields'=>[
                                            'keyword'=>[
                                                'type'=>'keyword'
                                            ]
                                        ]
                                    ]
                                ]
                            ]
                        ]
                    ]
                ],
            ],
        ];
        $client->put($url,$param);
        $this->info('============create template success============');

        $url = config('scout.elasticsearch.hosts')[0].'/'.$index;
        $param = [
            'json'=>[
                'settings'=>[
                    'refresh_interval'=>'5s',
                    'number_of_shards'=>1,
                    'number_of_replicas'=>0,
                ],

                'mappings'=>[
                    '_default_'=>[
                        '_all'=>[
                            'enabled'=>false
                        ]
                    ]
                ]
            ]
        ];

        $client->put($url,$param);
        $this->info('============create index:'.$index.' success============');
    }
}
